package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
/*
 * 最终版
 * ThreadLocal版
 * */
public class SqlSessionUtils3 {

    public SqlSessionUtils3() {
    }

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> t1 = new ThreadLocal<>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession(){

        return openSession(false);
    }
    public static SqlSession openSession(boolean autoCommit){
        SqlSession sqlSession = factory.openSession(autoCommit);
        t1.set(sqlSession);
        return sqlSession;
    }
    public static void commit(){
        SqlSession sqlSession = t1.get();
        if (sqlSession!=null){
            sqlSession.commit();
        }
    }
    public static void rollback(){
        SqlSession sqlSession = t1.get();

        if (sqlSession!=null){
            sqlSession.rollback();
        }
    }
    public static void close(){
        SqlSession sqlSession = t1.get();

        if (sqlSession!=null){
            sqlSession.close();
            t1.remove();
        }
    }


}
